<template>
  <div>
    <el-input type="file" @change="importf($event)"></el-input>
    <input type="file" @change="importf($event)" />
    <el-button @click="download">下载</el-button>
  </div>
</template>
<script>
import XLSX from "xlsx";
import axios from "axios";
export default {
  methods: {
    importf(obj) {
      let _this = this;
      var wb; //读取完成的数据
      var rABS = false; //是否将文件读取为二进制字符串
      var datajson = new Array();
      var updata;
      obj = obj.target;
      console.log(obj);
      if (!obj.files) {
        return;
      }
      var f = obj.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        var data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            //手动转化
            type: "base64"
          });
        } else {
          wb = XLSX.read(data, {
            type: "binary"
          });
        }
        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据
        datajson = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[1]]);
        _this.xlsxFormatter(datajson);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
      //
    },
    xlsxFormatter(data) {
      let tabledata = data.filter(ele => {
        return !!ele.xmmc;
      });
      // this.download(dishi,"地市.txt");
      // this.axiospost(tabledata)
      this.splitpost(this.axiospost, tabledata);
    },
    download(data, filename) {
      let str = `市名          县名称\r\n`;
      data.map(ele => {
        str = str + `${ele.sname}        ${ele.xname}\r\n`;
      });
      const file = new Blob([str]);
      const a = document.createElement("a");
      const url = URL.createObjectURL(file);
      a.href = url;
      a.download = `${filename}`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    },
    splitpost(fn, data) {
      let k = 20;
      let _this = this;
      if (data.length == 0) {
        console.log("发送完成");
        return false;
      } else {
        fn(data.splice(0, k));
        setTimeout(function() {
          return _this.splitpost(fn, data);
        }, 1000);
      }
    },
    axiospost(data) {
      data.forEach(element => {
              this.$axios({
        method: "post",
        url: "http://192.168.31.16:8080/pwjcxx/addAllList",
        data: element
      })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
      });

    }
  },
  mounted() {
    this.$axios({
      method: "get",
      url:
        "http://192.168.31.16:8080/loginSubmit?loginName=A001&password=123456"
    })
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>
